<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-100 px-4">
    <div class="w-full max-w-md bg-white p-8 rounded-2xl shadow-md">
      <h2 class="text-2xl font-bold mb-6 text-center text-gray-800">登录 / 注册</h2>
      <form @submit.prevent="handleLogin" class="space-y-4">
        <div>
          <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱：</label>
          <input
            id="email"
            v-model="email"
            type="email"
            required
            class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="请输入邮箱"
          />
        </div>
        <div>
          <label for="code" class="block text-sm font-medium text-gray-700 mb-1">验证码：</label>
          <div class="flex space-x-2">
            <input
              id="code"
              v-model="code"
              type="text"
              maxlength="6"
              required
              class="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="6位验证码"
            />
            <button
              type="button"
              @click="sendCode"
              :disabled="countdown > 0"
              class="px-3 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ countdown > 0 ? `${countdown} 秒后重试` : '获取验证码' }}
            </button>
          </div>
        </div>
        <button
          type="submit"
          class="w-full bg-green-500 text-white py-2 rounded-lg hover:bg-green-600 transition"
        >
          登录 / 注册
        </button>
      </form>
      <p v-if="message" class="mt-4 text-center text-sm text-red-500">{{ message }}</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onUnmounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const email = ref('')
const code = ref('')
const message = ref('')
const countdown = ref(0)
let timer: any = null

const isEmail = (val: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)

const sendCode = async () => {
  if (!isEmail(email.value)) {
    message.value = '请输入有效的邮箱地址'
    return
  }
  try {
    const res = await axios.post('http://127.0.0.1:3000/api/send-code', {
      email: email.value
    })
    message.value = res.data.message
    startCountdown()
  } catch (err: any) {
    message.value = err.response?.data?.error || '发送失败'
  }
}

const handleLogin = async () => {
  try {
    const res = await axios.post('http://127.0.0.1:3000/api/verify-code', {
      email: email.value,
      code: code.value
    })
    message.value = res.data.message
    localStorage.setItem('user_id', res.data.user_id)
    router.push('/add')
  } catch (err: any) {
    message.value = err.response?.data?.error || '登录失败'
  }
}

const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0 && timer) clearInterval(timer)
  }, 1000)
}

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

